package com.estronger.shopmanage.ui.home.presenter;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;

import android.util.Log;

import com.bumptech.glide.Glide;
import com.estronger.shopmanage.R;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.B1Login;
import com.estronger.shopmanage.bean.B8Wether;
import com.estronger.shopmanage.bean.B9Share;
import com.estronger.shopmanage.bean.BeanTaskSum;
import com.estronger.shopmanage.bean.GridItemBean;
import com.estronger.shopmanage.bean.MenuPermission;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.ui.aftermarket.AftermarketActivity;
import com.estronger.shopmanage.ui.grab.activity.GrabPondActivity;
import com.estronger.shopmanage.ui.order.activity.OrderEntryActivity;
import com.estronger.shopmanage.ui.order.activity.OrderQueryActivity;
import com.estronger.shopmanage.ui.order.activity.StatisticalActivity;
import com.estronger.shopmanage.ui.order.until.Tools;
import com.estronger.shopmanage.ui.install.BuildActivity;
import com.estronger.shopmanage.ui.install.pg.InstallPGActivity;
import com.estronger.shopmanage.ui.measure.MeasureActivity;
import com.estronger.shopmanage.ui.measure.pg.MeasurePGActivity;
import com.estronger.shopmanage.ui.othertask.activity.OtherTaskMainActivity;
import com.estronger.shopmanage.ui.send.SendActivity;
import com.estronger.shopmanage.ui.send.pg.DeliverPGActivity;
import com.estronger.shopmanage.utils.DataTools;
import com.estronger.shopmanage.utils.PrefUtils;
import com.estronger.shopmanage.view.RoundImageView;
import com.google.gson.Gson;
import com.orhanobut.hawk.Hawk;
import com.soonfor.evaluate.bean.EvaluateRankingBean;
import com.soonfor.evaluate.http.api.Request;
import com.soonfor.evaluate.http.httptools.AsyncUtils;
import com.soonfor.evaluate.tools.UserInfo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



public class MainPresenter implements AsyncUtils.AsyncCallback {

    private final int REQUEST_CODE_PGRIGHT = 10001;
    private final int REQUEST_CODE_NUMS = 10002;
    private final int REQUEST_CODE_ARTICLE = 10003;
    private final int REQUEST_CODE_WEATHER = 10004;
    private IMainView view;
    private List<GridItemBean> gridList;


    public MainPresenter(IMainView view) {
        this.view = view;
    }

    public List<GridItemBean> getGridList() {
        if (gridList == null) {
            gridList = new ArrayList<>();
        }
        return gridList;
    }

    /**
     * 获取GridView数据
     */
    public List<GridItemBean> getGridItemDatas() {
        if (gridList == null) {
            gridList = new ArrayList<>();
        } else if (gridList.size() > 0) {
            gridList.clear();
        }
        gridList.add(new GridItemBean(4, "测量", R.drawable.home_celiang_icon, R.drawable.home_celiang_icon, MeasureActivity.class, 0));
        gridList.add(new GridItemBean(6, "送货", R.drawable.home_songhuo_icon, R.drawable.home_songhuo_icon, SendActivity.class, 0));
        gridList.add(new GridItemBean(8, "安装", R.drawable.home_anzhuang_icon, R.drawable.home_anzhuang_icon, BuildActivity.class, 0));
        return gridList;
    }

    //添加其他任务
    public void addOtherTast(){
        if (gridList != null && gridList.size() > 0)
        gridList.add(new GridItemBean(9, "其它任务", R.mipmap.gd_icon, R.mipmap.gd_icon, OtherTaskMainActivity.class, 0));
        gridList.add(new GridItemBean(10, "抢单池", R.mipmap.qd_icon, R.mipmap.qd_icon, GrabPondActivity.class, 0));
        gridList.add(new GridItemBean(11, "扫一扫", R.drawable.sscan, R.drawable.sscan, null, 0));
    }

    /**
     * 派工相关按钮是否添加
     */
    public void addpgItems(MenuPermission mp) {
        try {
            if (mp != null) {
                boolean isExsit = false;
                for (int i = 0; i < gridList.size(); i++) {
                    if (i < gridList.size()) {
                        int menu_id = gridList.get(i).get_id();
                        if (menu_id == 0 || menu_id == 1 || menu_id == 2 || menu_id == 3 || menu_id == 5 || menu_id == 7) {
                            gridList.remove(i);
                        }
                    }
                }
                if (mp.getAdvance_order_add() == 1) {
                    gridList.add(new GridItemBean(0, "预订单录入", R.drawable.order_entry_icon, R.drawable.order_entry_icon, OrderEntryActivity.class, 0));
                }
                if (mp.getAdvance_order_query() == 1) {
                    gridList.add(new GridItemBean(1, "预订单查询", R.drawable.home_chaxun_icon, R.drawable.home_chaxun_icon, OrderQueryActivity.class, 0));
                }
                if (mp.getAdvance_order_statistics() == 1) {
                    gridList.add(new GridItemBean(2, "预订单统计", R.drawable.home_tongji_icon, R.drawable.home_tongji_icon, StatisticalActivity.class, 0));
                }
                if (mp.getPgme_sign() == 1) {
                    gridList.add(new GridItemBean(3, "测量派工", R.drawable.measure_icon, R.drawable.measure_icon, MeasurePGActivity.class, 0));
                }
                if (mp.getPgdlv_sign() == 1) {
                    gridList.add(new GridItemBean(5, "送货派工", R.drawable.delivery_icon, R.drawable.delivery_icon, DeliverPGActivity.class, 0));
                }
                if (mp.getPgIst_sign() == 1) {
                    gridList.add(new GridItemBean(7, "安装派工", R.drawable.setup_icon, R.drawable.setup_icon, InstallPGActivity.class, 0));
                }
                if (mp.getAfterSales_code() == 1){
                    gridList.add(new GridItemBean(12, "售后", R.drawable.icon_shouhou, R.drawable.icon_shouhou, AftermarketActivity.class, 0));
                }
            }
            Collections.sort(gridList, new Comparator<GridItemBean>() {
                public int compare(GridItemBean o1, GridItemBean o2) {
                    return o1.compareTo(o2);
                }
            });
        } catch (Exception e) {
        }
    }

    //获取头像
    public void getHeadPic(final Activity activity, final RoundImageView imageView) {
        try {
            if (MyApplication.login == null) {
                String loginData = PrefUtils.getString(activity, "loginData", "");
                if (!TextUtils.isEmpty(loginData)) {
                    MyApplication.login = new Gson().fromJson(loginData, B1Login.class);
                }
            }
            if (MyApplication.login.data.headpic != null) {
//                Glide.with(activity).
                MyApplication.imageLoader
                        .displayImage(NetManager.getDownloadURL() + "?filepath="
                                + MyApplication.login.data.headpic, imageView);
            }
        } catch (Exception e) {
//            NLogger.e("崩溃异常收集:" + e.getMessage());
        }
    }

    /**
     * 请求按钮是否显示权限
     */
    public void getPgRifht(Context mContext) {
        Map<String, String> params = new HashMap<>();
        params.put("sf_action", "getassignright");
        params.put("usercode", PrefUtils.getString(mContext, "userName", ""));
        AsyncUtils.post(mContext, UserInfo.COMMON_URL_BASE, params, REQUEST_CODE_PGRIGHT, true, this);
    }

    /**
     * 获取任务数量
     */
    public void getTaskNums(Context mContext) {
        Map<String, String> params = new HashMap<>();
        params.put("sf_action", "getusertasknum");
        params.put("usercode", PrefUtils.getString(mContext, "userName", ""));
        AsyncUtils.post(mContext, UserInfo.COMMON_URL_BASE, params, REQUEST_CODE_NUMS, true, this);
    }

    /**
     * 更新按钮上的数量
     */
    public void refreshItmeNums(BeanTaskSum sum) {
        try {
            if (sum != null) {
                for (int i = 0; i < gridList.size(); i++) {
                    switch (gridList.get(i).get_id()) {
                        case 3:
                            gridList.get(i).setNumber(sum.getMeasurenotassignnum());
                            break;
                        case 4:
                            gridList.get(i).setNumber(sum.getMeasurenum());
                            break;
                        case 5:
                            gridList.get(i).setNumber(sum.getDlvnotassignnum());
                            break;
                        case 6:
                            gridList.get(i).setNumber(sum.getDlvnum());
                            break;
                        case 7:
                            gridList.get(i).setNumber(sum.getIstnotassignnum());
                            break;
                        case 8:
                            gridList.get(i).setNumber(sum.getIstnum());
                            break;
                        case 9:
                            gridList.get(i).setNumber(sum.getPlanworknum());
                            break;
                        case 10:
                            gridList.get(i).setNumber(sum.getSnatchpoolnum());
                            break;
                        case 12:
                            gridList.get(i).setNumber(sum.getClaimnum());
                            break;
                    }
                }
                view.showNoEvalCustomerNum(sum.getStayappraisecstnum());
            }
        } catch (Exception e) {
        }
    }

    /**
     * 请求经验分享列表
     */
    public void getShareArticles(final Activity activity) {
        Map<String, String> params = new HashMap<>();
        params.put("sf_action", "getarticle");
        params.put("usercode", PrefUtils.getString(activity, "userName", ""));
        AsyncUtils.post(activity, UserInfo.COMMON_URL_BASE, params, REQUEST_CODE_ARTICLE, true, this);
    }

    /**
     * 获取城市代号
     */
    public void getCityCode(Activity activity) {
        new Thread() {
            @Override
            public void run() {
                try {
                    // 从 assets 中读取 JSON 数据
                    InputStream inputStream = activity.getAssets().open("city.json");
                    int size = inputStream.available();
                    byte[] buffer = new byte[size];
                    inputStream.read(buffer);
                    inputStream.close();
                    // 将 JSON 数据解析成 JSONArray 对象
                    JSONObject obj = new JSONObject(new String(buffer, "UTF-8"));
                    String cityCode = obj.getString(MyApplication.city);
                    MyApplication.cityID = cityCode;
                    getWeather();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 根据城市代号取气温天气信息
     * 所定位的城市代号
     */
    public void getWeather() {
        Map<String, String> params = new HashMap<>();
        params.put("sf_action", "getweather");
        params.put("position", MyApplication.cityID);
        AsyncUtils.post(MyApplication.mainActivity, UserInfo.COMMON_URL_BASE, params, REQUEST_CODE_WEATHER, true, this);
    }

    /**
     * 获取天气背景图片
     */
    public int getWeatherDrawable(String weatherData) {
        int resId = 0;
        if ("冰雹".equals(weatherData)) {
            resId = R.drawable.tianqi_bingbao_icon;
        } else if ("雷".equals(weatherData)) {
            resId = R.drawable.tianqi_lei_icon;
        } else if ("晴".equals(weatherData)) {
            resId = R.drawable.tianqi_qing_icon;
        } else if ("晴转阴".equals(weatherData)) {
            resId = R.drawable.tianqi_qing_icon;
        } else if ("沙尘暴".equals(weatherData)) {
            resId = R.drawable.tianqi_shachenbao_icon;
        } else if ("雾".equals(weatherData)) {
            resId = R.drawable.tianqi_wu_icon;
        } else if ("雪".equals(weatherData)) {
            resId = R.drawable.tianqi_xue_icon;
        } else if ("阴".equals(weatherData)) {
            resId = R.drawable.tianqi_yin_icon;
        } else if ("雨".equals(weatherData)) {
            resId = R.drawable.tianqi_yu_icon;
        }
        return resId;
    }

    //获取客户评价
    public void getEvaluateOverview(Activity mActivity) {
        Request.Evaluate.getEvaluateView(mActivity, this);
    }

    @Override
    public void success(final int requestCode, final String data) {
        try {
            switch (requestCode) {
                case REQUEST_CODE_PGRIGHT:
                    JSONObject object = new JSONObject(data);
                    MenuPermission mpRight = new MenuPermission();
                    mpRight.setPgme_sign(Tools.ToDefaultInt(object.getString("crm197_assign")));
                    mpRight.setPgdlv_sign(Tools.ToDefaultInt(object.getString("crm206_dlvassign")));
                    mpRight.setPgIst_sign(Tools.ToDefaultInt(object.getString("crm206_istassign")));
                    try {
                        mpRight.setAdvance_order_query(Tools.ToDefaultInt(object.getString("crm201_run")));
                        mpRight.setAdvance_order_add(Tools.ToDefaultInt(object.getString("crm201_add")));
                        mpRight.setAdvance_order_statistics(Tools.ToDefaultInt(object.getString("crm201_statistic")));
                        mpRight.setAfterSales_code(Tools.ToDefaultInt(object.getString("crm434_taskfinish")));
                    } catch (Exception e) {
                        e.getMessage();
                    }
                    Log.e("-------------",data);
                    addpgItems(mpRight);
                    view.refeshGrildView(REQUEST_CODE_PGRIGHT, true, mpRight);
                    //取任务数量
                    getTaskNums(MyApplication.mainActivity);
                    break;
                case REQUEST_CODE_NUMS:
                    BeanTaskSum sum = new Gson().fromJson(data, BeanTaskSum.class);
                    refreshItmeNums(sum);
                    view.refeshGrildView(REQUEST_CODE_NUMS, true, null);
                    break;
                case REQUEST_CODE_ARTICLE:
                    JSONArray ja = new JSONArray(data);
                    Gson gson = new Gson();
                    ArrayList<B9Share> shareList = new ArrayList<>();
                    if (ja != null && ja.length() > 0) {
                        for (int i = 0; i < ja.length(); i++) {
                            B9Share shareData = gson.fromJson(ja.getJSONObject(i).toString(), B9Share.class);
                            shareList.add(shareData);
                        }
                    }
                    if (shareList.size() > 0) {
                        view.showArticles(shareList, true);
                    }
                    break;
                case REQUEST_CODE_WEATHER:
                    try {
                        final B8Wether weather = new Gson().fromJson(data, B8Wether.class);
                        view.refreshWeather(weather);
                    } catch (Exception e) {
//                        NLogger.e("" + e.getMessage());
                    }
                    break;
                case Request.Evaluate.GET_EVALUATEVIEW://评价概况
                    DataTools.rankingBeans = new ArrayList<>();
                    B1Login.LoginData userBean = Hawk.get(UserInfo.LOGIN_USERINFO, null);
                    int ranking = -1;//我的排名
                    try {
                        JSONArray jag = new JSONArray(data);
                        if (jag != null && jag.length() > 0) {
                            for (int i = 0; i < jag.length(); i++) {
                                EvaluateRankingBean rankingBean = new Gson().fromJson(jag.getJSONObject(i).toString(), EvaluateRankingBean.class);
                                if (ranking < 0 && rankingBean.getFusercode().equals(userBean.getUsercode())) {
                                    ranking = i;
                                }
                                DataTools.rankingBeans.add(rankingBean);
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (DataTools.rankingBeans.size() > 0) {
                        view.setEvaluateInfoToView(DataTools.rankingBeans, ranking);
                    }
                    break;
            }

        } catch (Exception e) {
//            NLogger.e(e.getMessage());
        }

    }

    @Override
    public void fail(int requestCode, int statusCode, String data, String msg) {
        switch (requestCode) {
            case REQUEST_CODE_PGRIGHT:
                //取任务数量
                getTaskNums(MyApplication.mainActivity);
                break;
            case REQUEST_CODE_NUMS:
                view.refeshGrildView(REQUEST_CODE_NUMS, false, null);
                break;
            case REQUEST_CODE_ARTICLE:
                view.showArticles(null, false);
                break;
            case REQUEST_CODE_WEATHER:
                System.out.println("");
                break;
        }
    }

    //获取我的排行
    public void getMyRanking() {
        B1Login.LoginData userBean = Hawk.get(UserInfo.LOGIN_USERINFO, null);
        int ranking = -1;
        if (userBean != null && !userBean.getUsercode().equals("")) {
            for (int i = 0; i < DataTools.rankingBeans.size(); i++) {
                if (DataTools.rankingBeans.get(i).getFusercode().equals(userBean.getUsercode())) {
                    ranking = i;
                    break;
                }
            }
        }
        view.setEvaluateInfoToView(DataTools.rankingBeans, ranking);
    }
}
